package com.zhx.real.security.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理是否需要身份验证的controller
 *
 * @author zhx
 * @create 2017-11-02 10:50
 **/
@RestController
public class BrowserSecurityController {
	private final static Logger logger = LoggerFactory.getLogger(BrowserSecurityController.class);

	/**
	 * HttpSessionRequestCache spring 获取之前缓存的请求
	 */
	private RequestCache requestCache = new HttpSessionRequestCache();

	@RequestMapping("/v1/authentication/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	@ResponseBody
	public ResponseEntity requireAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		SavedRequest saveRequest = requestCache.getRequest(request, response);

		if(saveRequest != null) {
			String targetUrl = saveRequest.getRedirectUrl();

			logger.info("BrowserSecurityController 中 引发跳转的请求是:{}", targetUrl);
		}
		return ResponseEntity.status(401).body("访问的请求需要身份认证,请引导用户到登录页");
	}


	@GetMapping("/session/invalid")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public ResponseEntity sessionInvalid() {
		String message = "session过期";
		return ResponseEntity.ok(message);
	}
}
